package com.gok.kanmeituyun2.util.file;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * @Company
 * @Classname
 * @Description TODO  对SharedPreferences文件操作的类： 单例模式
 * @Author wbs
 * Date 2021.6.18 10:52
 * Version 1.0
 */
public class SharedPreferencesUtil {
    private Context context;
    private static SharedPreferencesUtil sp;

    //构造重载：私有化
    private SharedPreferencesUtil(Context context) {
        this.context = context;
    }

    /**
     * @param context
     * @return com.gok.kanmeituyun2.util.file.SharedPreferencesUtil
     * @methodName TODO 实现单例:对类外提供公共静态的方法，以取得此类的实例
     * @author wbs
     * @date 2021.6.18 11:03
     */
    public static SharedPreferencesUtil getInstance(Context context) {
        if (sp == null) {
            sp = new SharedPreferencesUtil(context);
        }
        return sp;
    }


    /**
     * @param account
     * @param pwd
     * @return boolean
     * @methodName TODO 写文件
     * @author wbs
     * @date 2021.6.18 10:54
     */
    public boolean writeToSharedPreferences(String account, String pwd) {
        try {
            SharedPreferences sp = context.getSharedPreferences(Constant.KMF_FILE, Context.MODE_PRIVATE);
            if (account.equals("") || pwd.equals("")) {
                sp.edit().putString(Constant.KMF_ACCOUNT_PWD_KEY, "").commit();
            } else {
                sp.edit().putString(Constant.KMF_ACCOUNT_PWD_KEY, account + ":" + pwd).commit();//必须提交，否则无法写入文件
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @param status
     * @return boolean
     * @methodName TODO 写入登录状
     * @author wbs
     * @date 2021.6.18 11:41
     */
    public boolean writeLoginStatus(boolean status) {
        try {
            SharedPreferences sp = context.getSharedPreferences(Constant.KMF_FILE, Context.MODE_PRIVATE);
            sp.edit().putBoolean(Constant.KMF_LOGIN_STATUS_KEY, status).commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @return boolean
     * @methodName TODO 读取登录状态
     * @author wbs
     * @date 2021.6.18 11:45
     */
    public boolean readLoginStatus() {
        SharedPreferences sp = context.getSharedPreferences(Constant.KMF_FILE, Context.MODE_PRIVATE);
        return sp.getBoolean(Constant.KMF_LOGIN_STATUS_KEY, false);
    }

}
